package problem71;

//71.简化路劲
//https://leetcode.cn/problems/simplify-path/?envType=study-plan-v2&envId=top-interview-150

import java.util.ArrayList;
import java.util.List;

class Solution {
    public String simplifyPath(String path) {
        //去除多余的'/'
        StringBuffer stPath = new StringBuffer();
        for(int i = 0; i<path.length(); i++) {
            char ch = path.charAt(i);
            if(stPath.length() == 0 || ch != '/') {
                stPath.append(ch);
            }else if(ch == '/' && stPath.charAt(stPath.length()-1) != '/' && i != path.length()-1) {
                stPath.append(ch);
            }
        }

        String[] dirs = stPath.toString().split("/");
        List<String> list = new ArrayList<>();
        for(int i = 0; i<dirs.length; i++) {
            if(dirs[i].equals("..")) {
                if(list.size() > 0) {
                    list.remove(list.size()-1);
                }
            }else if(!dirs[i].equals(".") && !dirs[i].equals("") ) {
                list.add(dirs[i]);
            }
        }

        StringBuffer ret = new StringBuffer();
        for(int i = 0; i<list.size(); i++) {
            ret.append("/");
            ret.append(list.get(i));
        }
        if(ret.length() == 0) ret.append("/");
        return ret.toString();
    }
}